<?php
namespace Beerus\Modules\DecoCompany\Controllers;

use Doraemon\model\DecoCompanyAuth;
use Doraemon\model\DecoCompanyIssue;
use Doraemon\model\DecoCompanyIssueAnswer;
use Illuminate\Support\MessageBag;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Tab;
use Encore\Admin\Widgets\Form;
use Illuminate\Http\Request;
use App\Pockets\GridDataModel as pGridDataModel;

class IssueController
{
    public function list(Request $request, Content $content)
    {
        $pageSize = $request->input("per_page", 20);
        $page = $request->input("page", 1);
        $params = $request->input();

        $search = [];
        $search["issue_status"] = DecoCompanyIssue::STATUS_NORMAL;
        $search["is_default"] = DecoCompanyIssue::ISSUE_DEFAULT;

        $order = [];
        if (isset($params['_sort']) && $params['_sort']) {
            $order[$params['_sort']['column']] = strtoupper($params['_sort']['type']);
        }

        $map['AND'] = $search;
        $map['ORDER'] = $order ?: ['edit_time' => 'DESC'];
        $map['LIMIT'] = [
            ($page - 1) * $pageSize,
            $pageSize
        ];
        $list = DecoCompanyIssue::listByCondition($map);
        $total = DecoCompanyIssue::countByCondition($search);

        $gridModel = new pGridDataModel($list, $total, [
            'perPage' => $pageSize
        ]);
        $gridList = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->paginate($gridModel->getPerPage());
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->disableFilter();

                $grid->column("id", 'ID')->sortable();
                $grid->column('issue_title', '标题')->width(200);
                $grid->column('example', '参考示例')->width(300);
                $grid->column("add_time", '添加时间')->display(function () {
                    return $this->add_time ? date("Y-m-d H:i:s", $this->add_time) : '';
                });
                $grid->column("edit_time", '修改时间')->display(function () {
                    return $this->edit_time ? date("Y-m-d H:i:s", $this->edit_time) : '';
                });
                $grid->column("admin_id", '操作人员')->display(function () {
                    return "<span style='width:80px;display: inline-block;'>".Admin::user()->find($this->admin_id)->name."</span>";
                });
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableDelete();
                    $actions->disableView();
                });
            });

        $tab = new Tab();
        $tab->add('默认问题列表', $gridList->render(), true);
        $content->row($tab);
        return $content
            ->header('常见问题')
            ->description(' ')
            ->breadcrumb(['text' => '默认问题列表']);
    }

    public function create(Request $request, Content $content, $id = 0)
    {
        $header = $id ? '编辑' : '新增';
        $row = [];
        if ($id) {
            $row = DecoCompanyIssue::getByCondition(['id'=>$id]);
        }
        $form = new Form($row);
        $tab = new Tab();
        $tab->add($header, $form);

        if ($id) {
            $form->hidden('id');
        }
        $form->text('issue_title', '标题')->required();
        $form->textarea('example', '参考示例')->required();

        $form->action('/admin/DecoCompany/issue/save');

        return $content
            ->header('常见问题')
            ->description('默认问题')
            ->breadcrumb(['text' => '默认问题'])
            ->body($tab);
    }

    public function save(Request $request)
    {
        $params = $request->input();
        unset($params['_token']);

        if (empty($params['issue_title']) || empty($params['example'])) {
            $error = new MessageBag([
                'title' => '标题和参考示例不能为空'
            ]);
            return back()->withInput()->with(compact('error'));
        }

        $data = [];
        $data['issue_title'] = trim($params['issue_title']);
        $data['example'] = trim($params['example']);
        $data['is_default'] = DecoCompanyIssue::ISSUE_DEFAULT;
        $data['admin_id'] = Admin::user()->id;

        if ($params['id']) {
            $res = DecoCompanyIssue::updateInfo($data, ['id'=>$params['id']]);
        } else {
            $res = DecoCompanyIssue::addInfo($data);
        }
        if ($res) {
            $success = new MessageBag([
                'title' => '操作成功'
            ]);
            return redirect("/admin/DecoCompany/issue/list")->with(compact('success'));
        } else {
            $error = new MessageBag([
                'title' => '操作失败，请稍后重试'
            ]);
            return back()->withInput()->with(compact('error'));
        }
    }

    public function all_issue(Request $request, Content $content)
    {
        $pageSize = $request->input("per_page", 20);
        $page = $request->input("page", 1);
        $params = $request->input();

        $search = [];
        $search["ans_status"] = DecoCompanyIssueAnswer::STATUS_NORMAL;
        if (!empty($params['uid'])) {
            $search['uid'] = $params['uid'];
        }

        $order = [];
        if (isset($params['_sort']) && $params['_sort']) {
            $order[$params['_sort']['column']] = strtoupper($params['_sort']['type']);
        }

        $map['AND'] = $search;
        $map['ORDER'] = $order ?: ['edit_time' => 'DESC'];
        $map['LIMIT'] = [
            ($page - 1) * $pageSize,
            $pageSize
        ];
        $list = DecoCompanyIssueAnswer::listByCondition($map);
        $total = DecoCompanyIssueAnswer::countByCondition($search);

        foreach ($list as &$item) {
            $issueRow = DecoCompanyIssue::getByCondition(['id'=>$item['issue_id']]);
            $item['issue_title'] = $issueRow['issue_title'];
            $item['example'] = $issueRow['example'];
        }
        unset($item);

        $gridModel = new pGridDataModel($list, $total, [
            'perPage' => $pageSize
        ]);
        $gridList = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->paginate($gridModel->getPerPage());
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->disableCreateButton();
                $grid->disableActions();

                $grid->filter(function($filter){
                    // 去掉默认的id过滤器
                    $filter->disableIdFilter();

                    $filter->equal('uid', '用户UID')->placeholder('请输入uid');
                    $filter->expand();
                });

                $grid->column("id", 'ID')->sortable();
                $grid->column("uid", '用户')->userBasicInfo();
                $grid->column('enterprise_name', '公司名称')->display(function () {
                    $info = DecoCompanyAuth::getByUid($this->uid);
                    return $info ? $info["enterprise_name"] : "";
                })->width(200);
                $grid->column('issue_title', '问题')->width(150);
                $grid->column('example', '参考示例')->width(300);
                $grid->column('answer', '回答')->width(300);
                $grid->column("edit_time", '修改时间')->display(function () {
                    return $this->edit_time ? date("Y-m-d H:i:s", $this->edit_time) : '';
                });
            });

        $tab = new Tab();
        $tab->add('问题列表', $gridList->render(), true);
        $content->row($tab);
        return $content
            ->header('常见问题')
            ->description(' ')
            ->breadcrumb(['text' => '问题列表']);
    }
}